import { useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { findNodePath } from '@/utils';
import SvgIcon from '@/components/SvgIcon';
import { useMenuStore } from '@/store/menuStore';

type itemProps = {
    title: any;
};

const SlBreadcrumb = () => {
    const { getMenuItems, isMenuLoaded } = useMenuStore();
    const navigate = useNavigate();
    const location = useLocation();
    const segments = location.pathname
        .split('/')
        .filter((segment) => segment !== ''); // 分割路径，并过滤掉空字符串
    const [items, setItems] = useState<any[]>([]);
    useEffect(() => {
        const menuItems = getMenuItems();
        if (menuItems && menuItems.length) {
            const data = findNodePath(
                menuItems,
                `/${segments.join('/')}`,
                'path',
            );
            setItems(data);
        }
    }, [isMenuLoaded, navigate]); // 依赖项包括location.pathname和userProfile.menus

    const onClickItem = (item: any) => {
        if (!item.redirect) return;
        navigate(item.redirect); // 使用navigate进行跳转
    };
    return (
        <div className={'flex items-center text-[14px]'}>
            {(items || []).map((item: any, index: number) => {
                return (
                    <div
                        key={`label_${index}`}
                        className={'flex items-center text-[14px]'}
                    >
                        {item.icon &&
                            typeof item.icon === 'string' &&
                            item.icon.includes('icon') && (
                                <SvgIcon
                                    iconClass={item.icon}
                                    svgClass={'mr-1 text-[#969799]'}
                                ></SvgIcon>
                            )}
                        <span
                            onClick={() => onClickItem(item)}
                            className={`${
                                item.redirect
                                    ? 'text-[#969799] cursor-pointer'
                                    : 'text-[#333333]'
                            }`}
                        >
                            {item.label}
                        </span>
                        {index !== items.length - 1 && (
                            <span
                                className={`${
                                    item.redirect
                                        ? 'text-[#969799]'
                                        : 'text-[#333333]'
                                } px-2`}
                            >
                                /
                            </span>
                        )}
                    </div>
                );
            })}
        </div>
    );
};

export default SlBreadcrumb;
